
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import ws.*;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;


public class ChatBean implements Serializable{
    private int chatId;
    private String message;
    

    public ChatBean() {
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
    public int getChatId() {
        return chatId;
    }

    public void setChatId(int chatId) {
        this.chatId = chatId;
    }
    
    public void postMessage(){
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        UserUI user = ( UserUI )session.getAttribute("User");
        ws.RoMaWS_Service service = new ws.RoMaWS_Service();
        ws.RoMaWS port = service.getRoMaWSPort();

        //JAX-WX Auth.
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WSUrl.wsUrl);
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList(loginBean.getName()));
        headers.put("Password", Collections.singletonList(loginBean.getPassword()));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        
        port.createChatMessage(1, message, user.getId());
        
        message = "";
    }
    
    public List<ChatMessageUI> getMessages(){
        ws.RoMaWS_Service service = new ws.RoMaWS_Service();
        ws.RoMaWS port = service.getRoMaWSPort();
        //JAX-WX Auth.
        FacesContext context = FacesContext.getCurrentInstance();
        LoginBean loginBean = (LoginBean) context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);
        Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WSUrl.wsUrl);
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList(loginBean.getName()));
        headers.put("Password", Collections.singletonList(loginBean.getPassword()));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        return port.getChatMessages(1);          
    }
    
    
    
    
}
